#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python常用模块库 
@File ：scanner.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2025/2/21 上午8:57 
"""

import hashlib
import os
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Iterator, Dict


class FileScanner:
	def __init__(self, max_workers: int = 4):
		self.executor = ThreadPoolExecutor(max_workers=max_workers)

	def scan(self, path: Path, exclude: list) -> Iterator[Dict]:
		"""并行扫描目录"""
		for root, dirs, files in os.walk(path):
			# 过滤排除目录
			dirs[:] = [d for d in dirs if not self._is_excluded(Path(root) / d, exclude)]

			for file in files:
				file_path = Path(root) / file
				if not self._is_excluded(file_path, exclude):
					yield self.executor.submit(self._get_metadata, file_path)

	def _is_excluded(self, path: Path, patterns: list) -> bool:
		return any(path.match(p) for p in patterns)

	def _get_metadata(self, path: Path) -> Dict:
		try:
			stat = path.stat()
			return {
				"path": path,
				"size": stat.st_size,
				"mtime": stat.st_mtime,
				"ctime": stat.st_ctime,
				"hash": self._calculate_hash(path),
				"inode": stat.st_ino
			}
		except Exception as e:
			return {"error": str(e), "path": path}

	def _calculate_hash(self, path: Path) -> str:
		hasher = hashlib.sha256()
		try:
			with path.open("rb") as f:
				for chunk in iter(lambda: f.read(128 * 1024), b""):
					hasher.update(chunk)
			return hasher.hexdigest()
		except Exception:
			return ""


class RealTimeWatcher:
	def __init__(self):
		pass  # 使用平台相关实现
